class List{
    constructor(){
        this.url = "http://localhost/project/data/goods.json";
        this.cont = document.querySelector("#cont");

        this.load();

        
    }
    load(){
        ajax({
            url:this.url
        }).then((res)=>{
            this.res = JSON.parse(res);
            this.display();
        })
    }
    display(){
        let str = "";
        for(var i=0;i<this.res.length;i++){
            str += `<div class="goods" index="${this.res[i].goodsId}">
                        <a href="goodsdetails.html?id=${this.res[i].goodsId}">
                            <img src="${this.res[i].img.largeImg[0]}" alt="">
                            <p class="name">${ this.res[i].name }</p>
                            <div class="youhui">${ this.res[i].youhui }</div>
                            <span>${this.res[i].price}</span>
                        </a>
                        <input type="button" value="加入购物车" class="add">
                    </div>`
        }
        this.cont.innerHTML = str;
    }
    addEvent(){
        var that = this;
        this.cont.onclick = function(eve){
            var e = eve || window.event;
            var tar = e.target || e.srcElement;
            if(tar.className === "add"){
                that.goodsId = tar.parentNode.getAttribute("index");
                that.setData();
            }
        }
    }
    setData(){
        // console.log(this.goodsId);
        var gm = localStorage.getItem("goodsMsg");
        if(gm === null){
            gm = [{
                goodsId:this.goodsId,
                num:1,
                msg:this.getData(this.goodsId)
            }];
        }else{
            gm = JSON.parse(gm);
            var zhuangtai = 0;
            for(var i=0;i<gm.length;i++){
                if(gm[i].goodsId === this.goodsId){
                    gm[i].num++;
                    zhuangtai = 1;
                    break;
                }
            }
            if(zhuangtai == 0){
                gm.push({
                    goodsId:this.goodsId,
                    num:1,
                    msg:this.getData(this.goodsId)
                })
            }
        }
        localStorage.setItem("goodsMsg",JSON.stringify(gm));
    }
    getData(id){
        for(var i=0;i<this.res.length;i++){
            if(this.res[i].goodsId === id){
                return this.res[i];
            }
        }
        return {};
    }
}

var gl=new List;
gl.addEvent();